package v1

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/noaway/heartbeat"
	"github.com/unknwon/com"
	"heyzhima-yt-cpu/pkg/app"
	"heyzhima-yt-cpu/pkg/e"
	"heyzhima-yt-cpu/pkg/logging"
	"heyzhima-yt-cpu/pkg/util"
	"heyzhima-yt-cpu/service/cpu_cards_service"
	"net/http"
	"strconv"
)

const (
	init_secret = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
	new_secret  ="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF22"
)








// @Summary Get a single config
// @Produce  json
// @Param zone path int true "zone"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/GetConfig [get]
func GetConfig(c *gin.Context) {
	appG := app.Gin{C: c}
	zone := com.StrTo(c.Query("zone") ).MustInt()
	valid := validation.Validation{}
	valid.Min(zone, 1, "zone")
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}
	c.JSON(200, gin.H{"init_secret":init_secret,"new_secret":new_secret,"msg":"","status":1})
	return
}


// @Summary Get a single card
// @Produce  json
// @Param id path int true "ID"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/card/{id} [get]
func GetCardInfo(c *gin.Context) {
	appG := app.Gin{C: c}
	zone := com.StrTo(c.Query("zone")).MustInt()
	code := com.StrTo(c.Query("code")).String()
	valid := validation.Validation{}
	valid.Min(zone, 1, "zone")
	valid.MinSize(code, 1, "code")
	fmt.Println(zone)
	fmt.Println(code)
	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}
	//smart_pass.blog_cpu_cards
	//Unknown column 'ims_cpu_cards.deleted_at' in 'where clause'
	cpuCardsService := cpu_cards_service.CpuCards{CardCode:code}
	exists, err := cpuCardsService.ExistByID()
	fmt.Println(exists)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_CPU_CARD_FAIL, nil)
		return
	}
	if !exists {
		appG.Response(http.StatusNotFound, e.ERROR_NOT_EXIST_CPU_CARD, nil)
		return
	}else{
		cardInfo,err:=cpuCardsService.GetCpuCardInfo(code,zone)
		fmt.Println(cardInfo)
		if err != nil {
			appG.Response(http.StatusInternalServerError, e.ERROR_GET_CPU_CARD_FAIL, nil)
			return
		}

		count:=len(cardInfo)
		var str string
		if count==1{
			var expired string
			created:=util.SStampToStr(cardInfo[0].CreatedAt)
			if cardInfo[0].CardExpired>0{
				expired=util.SStampToStr(cardInfo[0].CardExpired)
			}else{
				expired="无限期"
			}
			CardId := strconv.Itoa(cardInfo[0].CardId)
			str += "门卡ID:"+CardId+"\n"
			str += "住户:"+cardInfo[0].UserName+"/"+cardInfo[0].UserMobile+"\n"
			str += "地址:"+cardInfo[0].BuildingNamePath+"\n"
			str += "开卡时间:"+created+"\n"
			str += "过期时间:"+expired+"\n"
		}else if count>1{
			str = "该卡有"+strconv.Itoa(count)+"条记录，请到后台查看";
		}else{
			str = "该卡后台没有开通记录"
		}
		CardSecret, err := cpuCardsService.CpuCardsByCode()
		if err != nil {
			appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_CPU_CARD_FAIL, nil)
			return
		}
		abc:=make(map[string]interface{})
		abc["exist"]=1
		abc["secret"]=CardSecret
		abc["info"]="卡类型：CPU卡\n密钥："+CardSecret+"\n"+str
		fmt.Println(abc)
		c.JSON(200, gin.H{"status":1,"exist":1,"secret":CardSecret,"info":"卡类型：CPU卡\n密钥："+CardSecret+"\n"+str,"msg":""})
		return
	}
	c.JSON(200, gin.H{"status":1,"exist":0,"secret":0,"info":"未激活","msg":""})
	return
}

// @Summary Get multiple card
// @Produce  json
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/ping [get]
func Ping(c *gin.Context) {

	heart:=make(map[string]int)
	heart["status"]=1
	jsonDate,err:=json.Marshal(heart)
	if err != nil {
		fmt.Println(err)
	}
	name, spec := string(jsonDate), 15
	ht, err := heartbeat.NewTast(name, spec)

	if err != nil {
		fmt.Println(err)
	}
	// Run a new mission
	ht.Start(func() error {
		//Call the callback every 5 seconds
		fmt.Println(name)
		return nil
	})
	c.JSON(200, gin.H{"status":1})
	return
}

func ActiveCard(c *gin.Context){
	adb:=false
	appG := app.Gin{C: c}
	zone := com.StrTo(c.Query("zone")).MustInt()
	code := com.StrTo(c.Query("code")).String()
	valid := validation.Validation{}
	valid.Min(zone, 1, "zone")
	valid.MinSize(code, 1, "code")

	if valid.HasErrors() {
		app.MarkErrors(valid.Errors)
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	cpuCardsService := cpu_cards_service.CpuCards{CardCode:code}
	exists, err := cpuCardsService.ExistByID()
	fmt.Println(err)

	if err != nil {
		fmt.Println("卡异常")
		appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_CPU_CARD_FAIL, nil)
		return
	}
	if exists {
		fmt.Println("修改卡片")
		_, err := cpuCardsService.Update(new_secret)
		if err != nil {
			appG.Response(http.StatusInternalServerError, e.ERROR_UPDATE_CPU_CARD_FAIL, nil)
			return
		}else{
			fmt.Println("卡修改成功")
			adb=true
		}
	}else{
		fmt.Println("b")
		fmt.Println("卡不存在，添加卡")
		cpuCardsService := cpu_cards_service.CpuCards{
			CardCode  : code,
			CardSecret : new_secret,
			ZoneId     : zone,
			CreatedAt  : util.CurrentTime(),
			UpdatedAt  : util.CurrentTime(),
		}
		if err := cpuCardsService.Add(); err != nil {
			appG.Response(http.StatusInternalServerError, e.ERROR_ADD_CPU_CARD_FAIL, nil)
			return
		}else{
			fmt.Println("卡添加成功")
			adb=true
		}
	}
	CardsService := cpu_cards_service.Cards{CardCode:code}
	cardInfo,err:=CardsService.GetCardInfo(code)
	fmt.Println(cardInfo)
	fmt.Println("获取卡的原始信息")
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR_GET_CARD_FAIL, nil)
		return
	}
	count:=len(cardInfo)
	fmt.Println(count)
	fmt.Println("长度")
	if count>1 {
		fmt.Println("我来了")
		//1. 先更新门卡类型和密钥
		for k,v := range cardInfo {
			CardsService.Update(cardInfo[k].CardId, new_secret, "Y")
			res:=make(map[string]interface{})
			res["building_id"]=v.BuildingId
			res["zone_id"]=v.ZoneId
			res["cardId"]=v.CardId
			res["cardIsCpu"]=v.CardIsCpu
			res["cardCpuSecret"]=v.CardCpuSecret
			res["cardCode"]=v.CardCode
			res["cardExpired"]=v.CardExpired
			res["AccountId"]=v.AccountId

			CardsService.SendCard(res,118)
		}
	}else if count==1{
		fmt.Println("我等于一")
		fmt.Println(cardInfo[0].CardId)
		fmt.Println("我等于二")
		rs,err :=CardsService.Update(cardInfo[0].CardId, new_secret, "Y")
		if err != nil {
			appG.Response(http.StatusInternalServerError, e.ERROR_UPDATE_CARD_FAIL, nil)
			return
		}
		logging.Info(rs)
		res:=make(map[string]interface{})
		res["building_id"]=cardInfo[0].BuildingId
		res["zone_id"]=cardInfo[0].ZoneId
		res["cardId"]=cardInfo[0].CardId
		res["cardIsCpu"]=cardInfo[0].CardIsCpu
		res["cardCpuSecret"]=cardInfo[0].CardCpuSecret
		res["cardCode"]=cardInfo[0].CardCode
		res["cardExpired"]=cardInfo[0].CardExpired
		res["AccountId"]=cardInfo[0].AccountId

		CardsService.SendCard(res,118)
	}else{
		fmt.Println("什么也没了")
	}
	fmt.Println(adb)
	if adb==true{
		c.JSON(200, gin.H{"status":1,"exist":0,"msg":"激活成功"})
	}else{
		c.JSON(200, gin.H{"status":0,"exist":0,"msg":"数据库操作失败"})
	}
}